
// 用于拼接字符串（自动插入换行）并替换到代码文件的类
function myString(dfText) {
  this.val = dfText || ''
  this.add = text => (this.val += (text || '') + '\r\n')
  this.writeTo = (strCode,tag) => {
      return strCode.replace(new RegExp(`\\$\\$${tag},?`, 'g'), this.val.trimLeft())
  }
}

// 页面列的生成
function generatorColumns(COLUMNS,page,mainTable,filedMap){
  COLUMNS.add(`                columns: [`)
  page.table.columns.forEach(col=>{
    const colItem = filedMap[col.id]
    let colProp = ''
    if(mainTable.name == colItem.table) {
        colProp = window.$lowerFirst(colItem.field)
    }
    else{
        colProp = `${window.$lowerFirst(colItem.table)}_${colItem.field}`
    }
    const _width = col.isMinWidth ? `minWidth:${col.width}`:`width:${col.width}`
    let point = `                    {label:'${col.label}',rowid:'${colProp}',${_width},align:'${col.align}'`
    if(['radio','checkbox','select','selectMultiple','treeselect','layerselect',
      'datetime','createtime','modifytime',
      'companySelect','company',
      'departmentSelect','department',
      'userSelect','createuser','modifyuser','areaselect'].includes(colItem.type)){
      const colItem2 = window.$deepClone(colItem)
      delete colItem2.csType
      delete colItem2.label
      delete colItem2.span
      delete colItem2.display
      delete colItem2.disabled
      delete colItem2.default
      delete colItem2.table
      delete colItem2.field
      delete colItem2.prop
      delete colItem2.placeholder
      delete colItem2.multiple
      delete colItem2.isLogin
      delete colItem2.dateType
      delete colItem2.readonly
      delete colItem2.clearable
      delete colItem2.columns
      delete colItem2.isPage
      delete colItem2.height
      delete colItem2.width
      delete colItem2.key
      if(colItem2.dataType != '1'){
        delete colItem2.options
      }
      else{
        delete colItem2.dataCode
      }

      if(colItem2.dataType != '3'){
        delete colItem2.dataValueKey
        delete colItem2.dataLabelKey
        delete colItem2.upCtrl
        delete colItem2.dataIdKey
        delete colItem2.dataPIdKey
      }
      
      
      point += `,scheme:${JSON.stringify(colItem2)}`
    }

    point += '},'

    COLUMNS.add(point)
  })

  COLUMNS.add(`                ],`)
}

export const generatorAppList = (setting,temp)=>{
  let strCode = temp
  temp = null
  const {page,formInfo,dbTable} = setting

  // 获取表单字段
  const fileds = []
  const filedMap = {}
  formInfo.tabList.forEach(tab=>{
      fileds.push(...tab.components.filter(t=>!['gridtable','divider','btn','card','viewtable'].includes(t.type)))
  })
  fileds.forEach(item=>{
      filedMap[item.prop] = item
  })

  // 获取主表信息
  const mainTable = dbTable.find(t=>t.type == 'main')
  const mainKey = mainTable.columns.find(t=>t.isPrimary)


  // 表格
  let COLUMNS = new myString()
  generatorColumns(COLUMNS,page,mainTable,filedMap)
  strCode = COLUMNS.writeTo(strCode,'COLUMNS')
  COLUMNS = null

  // 排序字段设置
  

  let sidx = mainTable.columns[0].name
  if(page.table.sidx){
      if(mainTable.name == filedMap[page.table.sidx].table) {
        sidx = window.$lowerFirst(filedMap[page.table.sidx].field)
      }
      else{
        sidx = `${window.$lowerFirst(filedMap[page.table.sidx].table)}_${filedMap[page.table.sidx].field}`
      }
  }
  
  if(page.table.isDESC){
    sidx += ' DESC'
  }
  sidx = `"${sidx}"`
  strCode = strCode.replace(new RegExp(`\\$\\$SIDX?`, 'g'),sidx)
 

  // 按钮处理
  let ADDBTN = new myString()
  let HANDLEBTN = new myString()
  if(page.btns.findIndex(t=>t.prop == 'Add') != -1){
    ADDBTN.add("                return this.GET_BUTTON_AUTH('Add', this.moduleId)")
    HANDLEBTN.add("            handleAdd() {")
    HANDLEBTN.add(`                this.NAV_TO('./single?type=create', {title: '${setting.des}【新增】', moduleId: this.moduleId }, true)`)
    HANDLEBTN.add("            },")
  }
  else{
    ADDBTN.add("                return false")
  }

  strCode = ADDBTN.writeTo(strCode,'ADDBTN')
  ADDBTN = null



  let ROWBTNS = new myString()
  ROWBTNS.add('[')
  page.btns.forEach(t=>{
    if(t.prop == 'Edit'){
      ROWBTNS.add(`                    { prop: 'Edit', label: '编辑', type: 'primary' },`)
      HANDLEBTN.add("            handleEdit() {")
      HANDLEBTN.add("                this.$refs.popup.close()")
      HANDLEBTN.add(`                this.NAV_TO('./single?type=edit', {title: '${setting.des}【编辑】',keyValue: this.editRow.${window.$lowerFirst(mainKey.name)}, moduleId: this.moduleId }, true)`)
      HANDLEBTN.add("            },")
    }
    else if(t.prop == 'Delete'){
      ROWBTNS.add(`                    { prop: 'Delete', label: '删除', type: 'warn' },`)
      HANDLEBTN.add(`            async handleDelete() {`)
      HANDLEBTN.add(`                if (!(await this.CONFIRM('删除项目', '确定要删除该项吗？', true))) {`)
      HANDLEBTN.add(`                    return`)
      HANDLEBTN.add(`                }`)
      HANDLEBTN.add("                this.$refs.popup.close()")
      HANDLEBTN.add(`                this.LOADING('提交删除中…')`)
      HANDLEBTN.add(`                const success =  await this.HTTP_DELETE({url: "/${window.$lowerFirst(setting.moduleId)}/${window.$lowerFirst(setting.name)}/"+ this.editRow.${window.$lowerFirst(mainKey.name)}, errorTips: '删除失败'})`)
      HANDLEBTN.add('                this.HIDE_LOADING()')
      HANDLEBTN.add(`                if (success) {`)
      HANDLEBTN.add(`                    this.TOAST('删除成功', 'success')`)
      HANDLEBTN.add('                    this.fetchList()')
      HANDLEBTN.add(`                }`)
      HANDLEBTN.add(`            },`)
    }


    /*else if(t.prop == 'Details'){
      ROWBTNS.add(`                    { prop: 'Details', label: '详情' },`)
    }*/
  })
  ROWBTNS.add('                ],')
  strCode = ROWBTNS.writeTo(strCode,'ROWBTNS')
  ROWBTNS = null

  strCode = HANDLEBTN.writeTo(strCode,'HANDLEBTN')
  HANDLEBTN = null


  // 数据请求
  strCode = strCode.replace(new RegExp(`\\$\\$URL?`, 'g'),`/${window.$lowerFirst(setting.moduleId)}/${window.$lowerFirst(setting.name)}`)
 
  return strCode
}

